import os
import xml.etree.ElementTree as ET
from os.path import join
import random
import requests

import rou.constants as rc


def create_sumocfg(net_path, rou_path, user_id, task_id, resource):
    '''
        根据路由文件生成对应的sumocfg文件
    '''
    # path = os.path.dirname(os.getcwd())
    # DEFAULT_PATH = join(path, "webgl")
    cfg_path = join(rc.DEFAULT_PATH, str(user_id) + "_" + str(task_id) + "_" + str(resource) + rc.CONFIG_SUFFIX)
    # 创建xml
    configuration = ET.Element("configuration")
    input = ET.SubElement(configuration, "input")
    net_file = ET.SubElement(input, "net-file")
    route_files = ET.SubElement(input, "route-files")
    net_file.set("value", net_path)
    route_files.set("value", rou_path)
    tree = ET.ElementTree(configuration)
    # 将XML写入文件
    open(cfg_path, 'w').close()
    tree.write(cfg_path, encoding='utf-8', xml_declaration=True)
    return cfg_path


def download_file(url, file_path):
    response = requests.get(url)
    with open(file_path, "wb") as file:
        file.write(response.content)
    return file_path

def findRoute(sumo_net, startedgeID):
    single_edge = sumo_net.getEdge(startedgeID)
    if single_edge is not None:
        temp = [startedgeID]
        count = 0
        while single_edge is not None:
            edge_Bound = single_edge.getOutgoing()
            edgeids = list()
            for k, v in edge_Bound.items():
                edgeids.append(k.getID())
            if edgeids is not None and len(edgeids) > 0:
                # print(type(k.getID()), "type")
                try:

                    if ":" not in edgeids:
                        print(edgeids)
                        id = random.choice(edgeids)
                        temp.append(id)
                        single_edge = sumo_net.getEdge(id)
                except ValueError:
                    continue
                # break
            count += 1
            if len(temp) > 100 or count > 200:
                break
    return temp[-1]
